package com.adnaan.backend.controller.wechat;

import cn.dev33.satoken.stp.StpUtil;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.ChatHistory;
import com.adnaan.backend.mapper.ChatHistoryMapper;
import com.adnaan.backend.service.AiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/ai")
public class AiChatController {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private ChatHistoryMapper chatHistoryMapper;

    @Resource
    private AiService aiService;

    @GetMapping("/history")
    public Result<List<Map<String, Object>>> getChatHistory() {
        Long userId = StpUtil.getLoginIdAsLong();
        return Result.success(aiService.getHistory(userId));
    }

    @PostMapping("/addHistory")
    public Result<ChatHistory> saveChatHistory(@RequestBody ChatHistoryRequest request) throws JsonProcessingException {
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setTitle(request.getTitle());
        chatHistory.setMessages(objectMapper.writeValueAsString(request.getMessages()));
        chatHistory.setUserId(StpUtil.getLoginIdAsLong());

        chatHistoryMapper.insert(chatHistory);
        return Result.success(chatHistory);
    }

    @PostMapping("/saveHistory")
    public Result<ChatHistory> updateChatHistory(@RequestBody ChatHistoryRequest request) throws JsonProcessingException {
        ChatHistory chatHistory = chatHistoryMapper.selectById(request.id);

        if (chatHistory != null) {
            chatHistory.setTitle(request.getTitle());
            chatHistory.setMessages(objectMapper.writeValueAsString(request.getMessages()));

            chatHistoryMapper.updateById(chatHistory);
            return Result.success(chatHistory);
        }

        return Result.error();
    }

    @GetMapping("/delHistory")
    public Result<Void> deleteChatHistory(@RequestParam Long id) {
        int result = chatHistoryMapper.deleteById(id);
        if (result > 0) {
            return Result.success();
        }
        return Result.error();
    }

    @Data
    static class ChatHistoryRequest {
        private Long id;
        private String title;
        private List<ChatMessage> messages;
        private Long userId;
    }

    @Data
    static class ChatMessage {
        private String role;
        private String content;
        private boolean thinking;
    }
}